#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
#include<signal.h>
#include<sys/time.h>
//sigchld函数测试
//父进程使用sigchld完成对子进程的回收

void sighandler(int signo)
{
	printf("这是子进程中断信号[%d]\n",signo);
}
void waitchild(int signo)
{
	while(1)
	{
		pid_t wpid = waitpid(-1,NULL,WNOHANG);
		if(wpid>0)
		{
			printf("child is quit,wpid==[%d]\n",wpid);
		}
		else if(wpid == 0)
		{
			printf("child is living,wpid==[%d]\n",wpid);
			break;
		}
		else if(wpid == -1 )
		{
			printf("no child is living,wpid==[%d]\n",wpid);
			break;
		}
	}
}

int main()
{
	//创建多个子进程
	int i = 0;
	pid_t pid = 0;
	//先将SIGCHLD信号阻塞
	sigset_t mask;
	sigemptyset(&mask);
	sigaddset(&mask,SIGCHLD);
	sigprocmask(SIG_BLOCK,&mask,NULL);

	//signal(SIGCHLD,sighandler);
	for(i;i<3;i++)
	{
		pid = fork();
		if(pid < 0)
		{
			perror("fork error");
			return -1;
		}
		if(pid == 0)
		{
			printf("创建了第[%d]个子进程\n",i+1);
			break;
		}
	}
	//创建子进程
	if(i==0)
	{
		printf("第[%d]个子进程,pid=[%d],ppid=[%d]\n",i+1,getpid(),getppid());
		//while(1)
		//{
		sleep(1);
		//}
	}
	if(i==1)
	{
		printf("第[%d]个子进程,pid=[%d],ppid=[%d]\n",i+1,getpid(),getppid());
		//while(1)
		//{
		sleep(2);
		//}
	}
	if(i==2)
	{
		printf("第[%d]个子进程,pid=[%d],ppid=[%d]\n",i+1,getpid(),getppid());
		//while(1)
		//{
		sleep(3);
		//}
	}
	if(i==3)
	{
		printf("这是父进程,pid=[%d],ppid=[%d]\n",getpid(),getppid());
		//注册SIGCHLD信号处理函数
		struct sigaction act;
		act.sa_handler = waitchild;
		sigemptyset(&act.sa_mask);
		act.sa_flags = 0;
		sigaction(SIGCHLD,&act,NULL);

		//完成sigCHLD信号的注册后，解除对SIGCHLD信号的阻塞
		sigprocmask(SIG_UNBLOCK,&mask,NULL);

		while(1)
		{
			sleep(1);
		}
	}
	return 1;
}
